﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Nova.dataDataSetTableAdapters;
using System.Data;

namespace Nova
{
    /// <summary>
    /// Interaction logic for AddForm.xaml
    /// </summary>
    public partial class AddForm : Window
    {
        MainForm parent;
        int rowId;
        bool modification = false;

        public AddForm(MainForm parent)
        {
            InitializeComponent();
            if (parent != null)
                this.parent = parent;
            lblExam.Visibility = Visibility.Collapsed;
            cbExamResult.Visibility = Visibility.Collapsed;
            btnSave.Content = "Добавить";
            this.Title = "Добавление информации:";
            datePicker1.Text = DateTime.Now.ToString();
        }

        public AddForm(MainForm parent,Int32 id)
        {
            InitializeComponent();
            if (parent != null)
                this.parent = parent;
            this.rowId = id;            
            modification = true;
            lblExam.Visibility = Visibility.Visible;
            cbExamResult.Visibility = Visibility.Visible;
            btnSave.Content = "Сохранить";
            this.Title = "Изменение информации:";
            LoadData();
        }

        private void LoadData()
        {

            dataDataSet dataset = new dataDataSet();
            BudgetTableAdapter da = new BudgetTableAdapter();
            da.Fill(dataset.Budget);
            Nova.dataDataSet.BudgetRow row = dataset.Budget.Select("id = " + rowId)[0] as Nova.dataDataSet.BudgetRow;
            cbStudent.SelectedValue = row["Student_id"];
            cbGroups.SelectedValue = row["Group_id"];
            cbInstructor.SelectedValue = row["Instructor_id"];
            tbPaid.Text = row["TotalPaid"].ToString();
            tbPrice.Text = row["LessonPrice"].ToString();
            tbLessons.Text = row["TotalLessons"].ToString();
            tbLessonsHad.Text = row["LessonsHad"].ToString();
            datePicker1.Text = row["InscriptionDate"].ToString();
            switch (row["ExternalExamResult"].ToString())
            {
                case "Будет":
                    cbExamResult.SelectedIndex = 0;
                    break;
                case "Сдал":
                    cbExamResult.SelectedIndex = 1;
                    break;
                case "Внутренний":
                    cbExamResult.SelectedIndex = 2;
                    break;
                case "МРЭУ":
                    cbExamResult.SelectedIndex = 3;
                    break;
            }

            StudentsTableAdapter sda = new StudentsTableAdapter();
            dataDataSet sds = new dataDataSet();
            sda.Fill(sds.Students);
            Nova.dataDataSet.StudentsRow srow = sds.Students.FindByid(row.Student_id);
            tbName.Text = srow.Name;
            tbSurname.Text = srow.Surname;
            dpBirth.Text = srow.Birth.ToString();
            tbAdress.Text = srow.Adress;
            tbPhone.Text = srow.Phone;

            InstructorsTableAdapter ida = new InstructorsTableAdapter();
            dataDataSet ids = new dataDataSet();
            ida.Fill(ids.Instructors);
            Nova.dataDataSet.InstructorsRow irow = ids.Instructors.FindByid(row.Instructor_id);
            tbInsName.Text = irow.Name;
            tbAuto.Text = irow.Auto;
            tbInsSurname.Text = irow.Surname;
            tbInsPhone.Text = irow.Phone;
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (!modification)
            {
                if (tabControl1.SelectedIndex == 0)
                {
                    dataDataSet dataset = new dataDataSet();

                    if (cbStudent.SelectedValue != null && cbInstructor.SelectedValue != null && cbGroups.SelectedValue != null && tbPaid.Text != "" &&
                        tbPrice.Text != "" && tbPrice.Text != "" && datePicker1.Text !="")
                    {
                        int studentId = Convert.ToInt32(cbStudent.SelectedValue);
                        int instructorId = Convert.ToInt32(cbInstructor.SelectedValue);
                        int groupId = Convert.ToInt32(cbGroups.SelectedValue);
                        double totalpaid = Convert.ToDouble(tbPaid.Text.Replace('.', ','));
                        double lessonPrice = Convert.ToDouble(tbPrice.Text.Replace('.', ','));
                        int totalLessons = Convert.ToInt32(tbLessons.Text);
                        int lessonsHad = Convert.ToInt32(tbLessonsHad.Text);
                        DateTime inscriptionDate = Convert.ToDateTime(datePicker1.Text);

                        dataset.Budget.AddBudgetRow(studentId, instructorId, groupId, totalpaid, inscriptionDate, lessonsHad, totalLessons, lessonPrice, DateTime.Now, ExamResult.Будет.ToString(), DateTime.Now, ExamResult.Будет.ToString(), DateTime.Now);
                        BudgetTableAdapter da = new BudgetTableAdapter();
                        da.Update(dataset);
                    }
                    else {
                        MessageBox.Show("Невозможно сохранить. Проверьте введённые данные!");
                        return;
                    }
                }

                if (tabControl1.SelectedIndex == 1)
                {
                    dataDataSet dataset = new dataDataSet();
                    if (tbAdress.Text != "" && tbPhone.Text != ""
                      && tbSurname.Text != "" && tbName.Text != "" && dpBirth.Text !="")
                    {
                        string name = tbName.Text;
                        string surname = tbSurname.Text;
                        DateTime birth = Convert.ToDateTime(dpBirth.Text);
                        string adress = tbAdress.Text;
                        string phone = tbPhone.Text;
                        dataset.Students.AddStudentsRow(name, surname, birth, adress, phone);
                        StudentsTableAdapter da = new StudentsTableAdapter();
                        da.Update(dataset);
                    }
                    else
                    {
                        MessageBox.Show("Невозможно сохранить. Проверьте введённые данные!");
                        return;
                    }

                }

                if (tabControl1.SelectedIndex == 2)
                {
                    dataDataSet dataset = new dataDataSet();
                    if (tbInsName.Text != "" && tbAuto.Text != "" && tbInsSurname.Text != "")
                    {
                        string name = tbInsName.Text;
                        string auto = tbAuto.Text;
                        string surname = tbInsSurname.Text;
                        string phone = tbInsPhone.Text;
                        dataset.Instructors.AddInstructorsRow(name, surname, phone, auto);
                        InstructorsTableAdapter da = new InstructorsTableAdapter();
                        da.Update(dataset);
                    }
                    else {
                        MessageBox.Show("Невозможно сохранить. Проверьте введённые данные!");
                        return;
                    }

                }
                parent.status.Content = "Запись добавлена";
                this.DialogResult = true;
            }
            else {
                if (tabControl1.SelectedIndex == 0)
                {
                    if (cbStudent.SelectedValue != null && cbInstructor.SelectedValue != null && cbGroups.SelectedValue != null && tbPaid.Text != "" &&
                       tbPrice.Text != "" && tbPrice.Text != "" && datePicker1.Text != "")
                    {
                        dataDataSet dataset = new dataDataSet();
                        BudgetTableAdapter da = new BudgetTableAdapter();
                        da.Fill(dataset.Budget);

                        Nova.dataDataSet.BudgetRow row = dataset.Budget.FindByid(rowId);
                        row.Student_id = Convert.ToInt32(cbStudent.SelectedValue);
                        row.Instructor_id = Convert.ToInt32(cbInstructor.SelectedValue);
                        row.Group_id = Convert.ToInt32(cbGroups.SelectedValue);
                        row.TotalPaid = Convert.ToDouble(tbPaid.Text.Replace('.', ','));
                        row.LessonPrice = Convert.ToDouble(tbPrice.Text.Replace('.', ','));
                        row.TotalLessons = Convert.ToInt32(tbLessons.Text);
                        row.LessonsHad = Convert.ToInt32(tbLessonsHad.Text);
                        row.InscriptionDate = Convert.ToDateTime(datePicker1.Text);
                        row.ExternalExamResult = cbExamResult.Text;
                        row.LastRecordEditDate = DateTime.Now;

                        da.Update(dataset);
                    }
                    else
                    {
                        MessageBox.Show("Невозможно сохранить. Проверьте введённые данные!");
                        return;
                    }
                }
                if (tabControl1.SelectedIndex == 1)
                {
                    dataDataSet dataset = new dataDataSet();
                    BudgetTableAdapter da = new BudgetTableAdapter();
                    da.Fill(dataset.Budget);
                    Nova.dataDataSet.BudgetRow row = dataset.Budget.FindByid(rowId);

                    if (tbAdress.Text != "" && tbPhone.Text != ""
                      && tbSurname.Text != "" && tbName.Text != "" && dpBirth.Text != "")
                    {
                        StudentsTableAdapter sda = new StudentsTableAdapter();
                        dataDataSet sds = new dataDataSet();
                        sda.Fill(sds.Students);
                        Nova.dataDataSet.StudentsRow srow = sds.Students.FindByid(row.Student_id);

                        srow.Name = tbName.Text;
                        srow.Surname = tbSurname.Text;
                        srow.Birth = Convert.ToDateTime(dpBirth.Text);
                        srow.Adress = tbAdress.Text;
                        srow.Phone = tbPhone.Text;
                        sda.Update(sds);
                    }
                    else
                    {
                        MessageBox.Show("Невозможно сохранить. Проверьте введённые данные!");
                        return;
                    }
                }

                if (tabControl1.SelectedIndex == 2)
                {
                    dataDataSet dataset = new dataDataSet();
                    BudgetTableAdapter da = new BudgetTableAdapter();
                    da.Fill(dataset.Budget);
                    Nova.dataDataSet.BudgetRow row = dataset.Budget.FindByid(rowId);

                    if (tbInsName.Text != "" && tbAuto.Text != "" && tbInsSurname.Text != "")
                    {
                        InstructorsTableAdapter ida = new InstructorsTableAdapter();
                        dataDataSet ids = new dataDataSet();
                        ida.Fill(ids.Instructors);
                        Nova.dataDataSet.InstructorsRow irow = ids.Instructors.FindByid(row.Instructor_id);

                        irow.Name = tbInsName.Text;
                        irow.Auto = tbAuto.Text;
                        irow.Surname = tbInsSurname.Text;
                        irow.Phone = tbInsPhone.Text;

                        ida.Update(ids);
                    }
                    else
                    {
                        MessageBox.Show("Невозможно сохранить. Проверьте введённые данные!");
                        return;
                    }

                }
                parent.status.Content = "Изменения сохранены";
                this.DialogResult = true;
            }
        }

        private void LoadCombos()
        {
            StudentsDataProvider students = new StudentsDataProvider();
            cbStudent.DisplayMemberPath = "Surname";
            cbStudent.SelectedValuePath = "id";
            cbStudent.ItemsSource = students.GetStudents();
            InstructorsDataProvider instructors = new InstructorsDataProvider();
            cbInstructor.DisplayMemberPath = "Surname";
            cbInstructor.SelectedValuePath = "id";
            cbInstructor.ItemsSource = instructors.GetInstructors();
            GroupDataProvider groups = new GroupDataProvider();
            cbGroups.DisplayMemberPath = "Name";
            cbGroups.SelectedValuePath = "id";
            cbGroups.ItemsSource = groups.GetGroup();
        }

        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {
            if (this.DialogResult.Value)
            parent.RefreshList();
        }

        private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tabControl1.SelectedIndex == 0)
            {
                LoadCombos();
                if (modification)
                {
                    LoadData();
                }
            }
        }

        private void cbStudent_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;
        }

        private void cbInstructor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //LoadData();
        }

        private void cbGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            AddGroup form = new AddGroup();
            form.ShowInTaskbar = false;
            form.Owner = this;
            bool? result = form.ShowDialog();
            if (result.Value)
            {
                GroupDataProvider groups = new GroupDataProvider();
                cbGroups.DisplayMemberPath = "Name";
                cbGroups.SelectedValuePath = "id";
                cbGroups.ItemsSource = groups.GetGroup();
                MessageBox.Show("Группа добавлена", "Информация: ");
            }
        }

        private void cbStudent_LostFocus(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(cbStudent.Text))
            {
                if (cbStudent.SelectedItem == null)
                {
                    cbStudent.Text = string.Empty;
                    return;
                }
            }
        }

        private void cbInstructor_LostFocus(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(cbInstructor.Text))
            {
                if (cbInstructor.SelectedItem == null)
                {
                    cbInstructor.Text = string.Empty;
                    return;
                }
            }
        }

        private void cbGroups_LostFocus(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(cbGroups.Text))
            {
                if (cbGroups.SelectedItem == null)
                {
                    cbGroups.Text = string.Empty;
                    return;
                }
            }
        }

        private void cbExamResult_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;
        }
    }
}
